﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LPV_POS.In;
using LPV_POS.mh_pos.mh_cauhinh;
using LPV_POS.mh_pos.mh_ban_hang;
using LPV_POS.Module;
using DevExpress.XtraLayout;
using System.Resources;
using System.Globalization;



namespace LPV_POS.mh_pos
{
    public partial class mh_banhang : DevExpress.XtraEditors.XtraForm
    {
        CultureInfo culture;
        string str_lang = "";
        thuvien tv;
        DataTable tb;

        string[] s;
        object[] o;
        System.Threading.Thread thrd_TEST;//-------------31/05/2012--------------

        #region "Muti language"
        private void SetLanguage_banhang(string cultureName)
        {
            try
            {
                cpublic ocpublic = new cpublic();
                culture = CultureInfo.CreateSpecificCulture(cultureName);
                ResourceManager rm = new ResourceManager("LPV_POS.Muti_language.MyResource", typeof(mh_banhang).Assembly);
                lblTrangChu_sodoban.Text = rm.GetString("trangchu", culture);

                if (ocpublic.Registry_Get(lblDatBan_sodoban.Name) == "True")
                    lblDatBan_sodoban.Text = rm.GetString("datban", culture);
                else
                    lblDatBan_sodoban.Text = "";

                if (ocpublic.Registry_Get(lblTachGopBan_sodoban.Name) == "True")
                    lblTachGopBan_sodoban.Text = rm.GetString("tachgopban", culture);
                else
                    lblTachGopBan_sodoban.Text = "";

                if (ocpublic.Registry_Get(lblTachGopPhieu_sodoban.Name) == "True")
                    lblTachGopPhieu_sodoban.Text = rm.GetString("tachgopphieu", culture);
                else
                    lblTachGopPhieu_sodoban.Text = "";

                if (ocpublic.Registry_Get(lblChuyenBan_sodoban.Name) == "True")
                    lblChuyenBan_sodoban.Text = rm.GetString("chuyenban", culture);
                else
                    lblChuyenBan_sodoban.Text = "";

                if (ocpublic.Registry_Get(lblKhachhang_sodoban.Name) == "True")
                    lblKhachhang_sodoban.Text = rm.GetString("khachhang", culture);
                else
                    lblKhachhang_sodoban.Text = "";

                if (ocpublic.Registry_Get(lblMoKet_sodoban.Name) == "True")
                    lblMoKet_sodoban.Text = rm.GetString("thekhachhang", culture);
                else
                    lblMoKet_sodoban.Text = "";

                if (ocpublic.Registry_Get(lblInHoaDon_sodoban.Name) == "True")
                    lblInHoaDon_sodoban.Text = rm.GetString("inhoadon", culture);
                else
                    lblInHoaDon_sodoban.Text = "";

                if (ocpublic.Registry_Get(lblInLaiHoaDon_sodoban.Name) == "True")
                    lblInLaiHoaDon_sodoban.Text = rm.GetString("inlaihoadon", culture);
                else
                    lblInLaiHoaDon_sodoban.Text = "";

                if (ocpublic.Registry_Get(lbel_moket1.Name) == "True")
                    lbel_moket1.Text = rm.GetString("moket", culture);
                else
                    lbel_moket1.Text = "";

                if (ocpublic.Registry_Get(lbl1_sodoban.Name) == "True")
                    lbl1_sodoban.Text = rm.GetString("sokhach", culture);
                else
                    lbl1_sodoban.Text = "";

                if (ocpublic.Registry_Get(label8_sodoban.Name) == "True")
                    label8_sodoban.Text = rm.GetString("nhanvienphucvu", culture);
                else
                    label8_sodoban.Text = "";
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString(), "Note");
            }
            
        }  

        #endregion


        public mh_banhang(string sTenCongTy)
        {

            InitializeComponent();
            culture = CultureInfo.CurrentCulture;
            lbel_tencongty.Text = sTenCongTy;
        }

        enum chon
        {
            None,
            Tach_Gop_Ban,
            Tach_Gop_Phieu,
            Chuyen_Ban,
            In_Hoa_Don,
            Khach_Hang,
            Dat_Ban, //đặt bàn
            Dat_Ban_Huy, //Hủy đặt bàn
            The_Khach_Hang,
            NhanVien_PhucVu,
            So_Khach
        }

        #region "   Property"
        chon ochon = new chon();

        private Boolean bLoadform = false;
        //private Point startPoint;
        private System.Windows.Forms.Control Control_Current = null;
        #endregion

        private int iDM_BAN_DAT_BAN_ID = -1;
        #region "   mh_banhang_Load"
        private void mh_banhang_Load(object sender, EventArgs e)
        {
             cpublic ocpublic = new cpublic();
             str_lang = ocpublic.Registry_Get("mh_main_lang");
             if (str_lang == "")
                 str_lang = "vi-VN";
             SetLanguage_banhang(str_lang);
           // SetLanguage_banhang("en-US");
             //
             if (ocpublic.Registry_Get("chkSo_Khach_Tren_Ban") + "" != "True")
                 lbl1_sodoban.Text = "";
             if (ocpublic.Registry_Get("chkNhan_Vien_Phuc_Vu") + "" != "True")
                 label8_sodoban.Text = "";
            
            //mh_dmkhachhang omh_dmkhachhang = new mh_dmkhachhang();
            
            //string skhachhang_op = new cpublic().Registry_Get(omh_dmkhachhang.Name + omh_dmkhachhang.txtkhachhang_optionbc.Name);
            
            //if (skhachhang_op != "")
            //    lblKhachhang_sodoban.Text = skhachhang_op;
            
            #region "   Nếu là SERVER"
            try
            {
                
                Boolean bPOSMayChu = new cpublic().Registry_Get("POSMayChu") + "" == "True";
                
                if (bPOSMayChu)
                {
                    
                    String strHostName = System.Net.Dns.GetHostName();
                    
                    System.Net.IPHostEntry oIPHostEntry = System.Net.Dns.GetHostByName(strHostName);
                    
                    System.Net.IPEndPoint oIPEndPoint = new System.Net.IPEndPoint(oIPHostEntry.AddressList[0], 6666);
                    
                    System.Threading.Thread oThread = new System.Threading.Thread(ReceiveData);
                    
                    oThread.IsBackground = true;
                    
                    oThread.Start();
                    
                }
            }
            catch (Exception ex)
            {
                if (ocpublic.Registry_Get("chkCrystalReport_Display") + "" == "True")
                    MessageBox.Show("Nếu là SERVER\n" + ex.Message);
            }
            #endregion
           
            tv = new thuvien();
            s = new string[] { "@flag" };
            o = new object[] { 6 };
            tb = tv.SP_SelectDataTable("sp_BH_CAU_HINH", s, o);
            
            this.Load_Menu_Bottom();
            
            timer1.Enabled = false;
            this.ShowData_Grd();
            
            int iHandle = Load_KhuVuc_Default();
            
            bLoadform = true;
            if (iHandle >= 0 && gvKhuVuc.FocusedRowHandle != iHandle)
            {
                gvKhuVuc.FocusedRowHandle = iHandle;
                gvKhuVuc.SelectRow(iHandle);
            }
            else if (iHandle >= 0 && gvKhuVuc.FocusedRowHandle == iHandle)
            {
                gvKhuVuc.FocusedRowHandle = iHandle;
                gvKhuVuc.SelectRow(iHandle);
                this.gridView1_FocusedRowChanged(null, null);
            }
            else
                this.gridView1_FocusedRowChanged(null, null);

            timer1.Enabled = true;
            //this.lblVaoCa_Click(null, null);
            
            this.LoadCaLamViec();
            
            //
            bLoadform = true;
            
        }
        #endregion
        static string sMAKHUVUC_static = "";
        private static void ReceiveData()
        {
             try//----------29/05/2012---------------------
            {
            System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient(7777);
            while (true)
            {
                try
                {
                    System.Net.IPEndPoint anyIP = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 7777);
                    byte[] data = client.Receive(ref anyIP);
                    sMAKHUVUC_static = Encoding.UTF8.GetString(data);
                    sMAKHUVUC_static = sMAKHUVUC_static.Trim();
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
            }
            }
             catch (Exception) { }
        }

        #region "   ShowData"
        void ShowData(string _MAKHUVUC)
        {
            cpublic ocpublic = new cpublic();
            //xóa hết control nằm trong Panel "pnlSoDoBan"            
            Boolean iHienThi_SoKhach = ocpublic.Registry_Get("chkSo_Khach_Tren_Ban") == "True";//2011.12.19
            Boolean iHienThi_TongTien = ocpublic.Registry_Get("chkHienThi_TongTien_TrenBan") == "True";//2011.12.19
            Boolean iHienThi_NHANVIEN = ocpublic.Registry_Get("chkNhan_Vien_Phuc_Vu") == "True";//2011.12.19

            DataTable tbDM_BAN = new thuvien().SP_SelectDataTable("sp_mh_banhang",
                                                                new string[] { "@MAKHUVUC", "@flag", "@HienThi_SoKhach_TrenBan", "@HienThi_TongTien_TrenBan", "@HienThi_NHANVIEN_PHUCVU" },
                                                                new object[] { _MAKHUVUC, 1, iHienThi_SoKhach, iHienThi_TongTien, iHienThi_NHANVIEN });

            
            //Font _font = new Font("Times New Roman", 13, FontStyle.Bold, GraphicsUnit.Point);//9999

            //pnlSoDoBan.Controls.Clear();
            this.Reset_pnlSoDoBan();
            int ik = 0;

            Boolean iKeo_Tha_Ban = ocpublic.Registry_Get("Keo_Tha_Ban") + "" == "True";
            foreach (DataRow dr in tbDM_BAN.Rows)
            {
                System.Windows.Forms.Control ctrl = this.getPanel(dr, iKeo_Tha_Ban, iHienThi_SoKhach, iHienThi_TongTien);

                this.SetHinhAnh(dr["HINH_NEN"] + "", ctrl, int.Parse("0" + dr["TRANGTHAI"] + ""));

                //ocpublic.BoGoc_Control(ctrl, Color.FromArgb(254, 255, 153), ctrl.ForeColor, Color.Black, _font, true);////9999

                pnlSoDoBan.Controls.Add(ctrl);
                ik++;
                if (ik == 100)
                    return;
            }
            pnlSoDoBan.Refresh();
        }

        void SetHinhAnh(string sSaveFolder, System.Windows.Forms.Control ctrl, int _thang_thai)
        {
            if (sSaveFolder == "")
                sSaveFolder = "Ban_Cafe";
            if (ctrl.Region != null)
            { //Hinh tron
                string sFileTron = Application.StartupPath + "\\hinh_anh\\" + sSaveFolder + "\\mat_ban_Tron_" + (_thang_thai + 1) + ".PNG";
                if (new System.IO.FileInfo(sFileTron).Exists)
                    ctrl.BackgroundImage = Image.FromFile(sFileTron);
            }
            else
            {
                //Hình Vuông
                string sFileVuong = Application.StartupPath + "\\hinh_anh\\" + sSaveFolder + "\\mat_ban_Vuong_" + (_thang_thai + 1) + ".PNG";
                if (new System.IO.FileInfo(sFileVuong).Exists)
                    ctrl.BackgroundImage = Image.FromFile(sFileVuong);

                //Hình Đứng
                sFileVuong = Application.StartupPath + "\\hinh_anh\\" + sSaveFolder + "\\dung_" + (_thang_thai + 1) + ".PNG";
                if (new System.IO.FileInfo(sFileVuong).Exists && ctrl.Size.Width < ctrl.Size.Height)
                    ctrl.BackgroundImage = Image.FromFile(sFileVuong);

                //Hình Ngang
                sFileVuong = Application.StartupPath + "\\hinh_anh\\" + sSaveFolder + "\\ngang_" + (_thang_thai + 1) + ".PNG";
                if (new System.IO.FileInfo(sFileVuong).Exists && ctrl.Size.Width >= ctrl.Size.Height)
                    ctrl.BackgroundImage = Image.FromFile(sFileVuong);
            }
        }
        #endregion

        #region "   ShowData_Grd"
        void ShowData_Grd()
        {//OBJID
            DataTable tbDM_KHUVUC = new thuvien().SP_SelectDataTable("sp_mh_banhang", new string[] { "@flag" }, new object[] { 2 });
            grdKhuVuc.DataSource = tbDM_KHUVUC;
        }
        #endregion

        #region "   Label_Click"
        void Label_Click(object sender, EventArgs e)
        {
            //if (Variable.username != "")
            {
                string _sMaBan = "";
                try
                {
                    Control_Current = (System.Windows.Forms.Control)sender;
                    _sMaBan = Control_Current.Tag + "";
                }
                catch (Exception ex)
                {
                    string s = ex.Message;
                }
                string sMa_The_VIP = "";

                #region "   chon.NhanVien_PhucVu"
                if (ochon == chon.NhanVien_PhucVu)
                {
                    if (_sMaBan != "")
                    {
                        DataTable tbPhieu = this.getTable_Phieu(_sMaBan + "", "");
                        if (tbPhieu.Rows.Count == 1)
                        {
                            mh_dmnhanvien omh_dmnhanvien = new mh_dmnhanvien();
                            omh_dmnhanvien.m_nhanvien_baocao = true;
                            DataRow dr = omh_dmnhanvien.ShowForm();
                            string sSQL = "UPDATE BH_PHIEU_TMP SET NHANVIEN_PHUCVU = N'" + dr["OBJNAME"] + "' WHERE DM_BAN_MA = '" + _sMaBan + "'";
                            new thuvien().SP_Update("SP_EXECUTESQL", new string[] { "@sSQL"}, new object[] { sSQL});
                            this.gridView1_FocusedRowChanged(null, null);
                        }
                    }
                    this.setNoneMesssage();
                    ochon = chon.None;
                    return;
                }
                #endregion

                #region "   chon.So_Khach"
                if (ochon == chon.So_Khach)
                {
                    if (_sMaBan != "")
                    {
                        mh_so omh_so = new mh_so(false, "Nhập số khách");
                        int isokhach = omh_so.ShowForm();
                        if (omh_so.DialogResult == DialogResult.OK)
                        {
                            string sSQL = "UPDATE BH_PHIEU_TMP SET SO_KHACH = " + isokhach + " WHERE DM_BAN_MA = '" + _sMaBan + "'";
                            new thuvien().SP_Update("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { sSQL });
                            this.gridView1_FocusedRowChanged(null, null);
                        }
                    }
                    this.setNoneMesssage();
                    ochon = chon.None;
                    return;
                }
                #endregion

                #region "   chon.Khach_Hang"
                if (ochon == chon.Khach_Hang)
                {
                    //
                    this.lblKhachhang_Click(null, null);
                    //mh_so omh_so = new mh_so(false,"Thẻ khách hàng");
                    //omh_so.eClick += new EventHandler(Kiem_Tra_The);
                    //omh_so.ShowDialog();
                    //if (omh_so.DialogResult != DialogResult.OK)
                    //    return;

                    //sMa_The_VIP = omh_so.txt_ketqua.Text;

                    mh_dmkhachhang omh_dmkhachhang = new mh_dmkhachhang();
                    DataRow dr = omh_dmkhachhang.ShowForm_fromBanHang(Control_Current.Text);

                    if ((omh_dmkhachhang.DialogResult != DialogResult.OK) || dr == null)
                    {
                        sMa_The_VIP = "";
                        return;
                    }
                    sMa_The_VIP = dr["THEKHACHHANG"] + "";
                    //tbBH_PHIEU_TMP.Rows[0]["CUSTOMER_ID"] = sMaThe_VIP;
                }
                #endregion

                #region Chọn thẻ khách hàng

                if (ochon == chon.The_Khach_Hang)
                {
                    this.lblMoKet_Click(null, null);
                    LPV_POS.mh_pos.mh_danhmuc.frmDM_THE_VIP frm = new LPV_POS.mh_pos.mh_danhmuc.frmDM_THE_VIP();
                    string SoThe=frm.ShowForm();
                    if ((frm.DialogResult != DialogResult.OK) || SoThe + "" == "")
                    {
                        sMa_The_VIP = "";
                        return;
                    }
                    sMa_The_VIP = SoThe + "";
                }

                #endregion

                if (ochon == chon.None)// && Variable.username != ""
                {
                    string Ma_Phieu = "";

                    thuvien othuvien = new thuvien();
                    #region "   ko xai"
                    //string sSQL = "SELECT b.* " +
                    //              "FROM DM_BAN b " +
                    //              " INNER JOIN DM_BAN_DAT_BAN c ON c.DM_BAN_ID = b.OBJID AND c.ISDELETE = 0" +//ISDELETE = 0 hien tai dang co DAT BAN
                    //              " WHERE OBJID LIKE '" + _sMaBan + "'";

                    //DataTable tbDM_Ban = othuvien.SP_SelectDataTable("SP_EXECUTESQL",
                    //                                                    new string[] { "@sSQL" },
                    //                                                    new object[] { sSQL });
                    ////Boolean iorder_Cho_Khach_Dat_Ban = false;
                    //if (tbDM_Ban.Rows.Count > 0)
                    //{
                    //    //string strangthai = tbDM_Ban.Rows[0]["TRANGTHAI"] + "";

                    //    //if (strangthai == "2")//BAN DANG CO NGUOI DAT                            
                    //    //{
                    //    //DataTable tbDM_BAN_DAT_BAN = othuvien.SP_SelectDataTable("sp_DM_BAN_DAT_BAN",
                    //    //                                                        new string[] { "@flag", "@DM_BAN_ID" },
                    //    //                                                        new object[] { 4, _sMaBan });

                    //    // dat ban aaa
                    //    if (tbDM_Ban.Rows[0]["TRANGTHAI"] + "" == "2")
                    //    {
                    //        mh_banhang_CT7_DatBan_order omh_banhang_CT7_DatBan_order = new mh_banhang_CT7_DatBan_order();
                    //        iorder_Cho_Khach_Dat_Ban = omh_banhang_CT7_DatBan_order.ShowForm();
                    //    }
                    //    //}
                    //}
                    #endregion

                    #region "   sPHAI_VAO_CA_KHI_BAN_HANG"
                    string sPHAI_VAO_CA_KHI_BAN_HANG = Variable.tbBH_CAU_HINH.Rows[0]["PHAI_VAO_CA_KHI_BAN_HANG"] + "";
                    if (sPHAI_VAO_CA_KHI_BAN_HANG == "True")
                    {
                        mh_so omh_so = new mh_so(true, "Mã đăng nhập");
                        omh_so.eClick += new EventHandler(DangNhap);
                        omh_so.ShowDialog();

                        if (omh_so.DialogResult != DialogResult.OK)
                            return;
                        this.LoadCaLamViec();
                    }
                    #endregion

                    #region "   CHO_PHEP_MO_BAN_CA_KHAC"
                    DataTable tbPhieu = this.getTable_Phieu(_sMaBan + "", "");
                    if (tbPhieu.Rows.Count > 0 && tbPhieu.Select("NGUOI_LAP LIKE '" + Variable.username + "'").Length == 0)
                    {
                        string sCHO_PHEP_MO_BAN_CA_KHAC = Variable.tbBH_CAU_HINH.Rows[0]["CHO_PHEP_MO_BAN_CA_KHAC"] + "";
                        if (sCHO_PHEP_MO_BAN_CA_KHAC == "False")
                        {
                            new mh_thongbao("Bàn này không phải bàn của CA " + Variable.username, 2).ShowDialog();
                            return;
                        }
                    }
                    #endregion

                    #region "   mh_banhang_CT_ChonPhieu"
                    if (tbPhieu.Rows.Count > 1)
                    {
                        mh_banhang_CT_ChonPhieu omh_banhang_CT_ChonPhieu = new mh_banhang_CT_ChonPhieu(_sMaBan + "");
                        Ma_Phieu = omh_banhang_CT_ChonPhieu.ShowForm();
                        if (omh_banhang_CT_ChonPhieu.DialogResult == DialogResult.Cancel)
                            return;
                    }
                    else if (tbPhieu.Rows.Count == 1)
                        Ma_Phieu = tbPhieu.Rows[0]["OBJID"] + "";
                    #endregion
                    /////////////////////////////////////

                    #region "   mh_banhang_CT -- ko xai"
                    //mh_banhang_CT omh_banhang_CT = new mh_banhang_CT(lbel_tencongty.Text, lblcalamviec.Text, iorder_Cho_Khach_Dat_Ban);
                    //omh_banhang_CT.sBAN_MA = _sMaBan + "";
                    //omh_banhang_CT.sPhieu_Ma = Ma_Phieu;
                    //omh_banhang_CT.sMaThe_VIP = sMa_The_VIP;
                    //omh_banhang_CT.sKhuVucMa = this.GetSelectedValues(gvKhuVuc, "OBJID");

                    ////omh_banhang_CT.bDaVaoCa = bDaVaoCa;
                    //omh_banhang_CT.ShowInTaskbar = false;
                    //omh_banhang_CT.ShowDialog();
                    //if (omh_banhang_CT.DialogResult == DialogResult.OK)
                    //{
                    //    this.gridView1_FocusedRowChanged(null, null);
                    //}
                    //else if (omh_banhang_CT.DialogResult == DialogResult.Cancel)
                    //{
                    //    this.DialogResult = DialogResult.OK;
                    //    this.Close();
                    //}
                    #endregion

                    

                    #region "   mh_banhang_CT"
                    mh_banhang_CT omh_banhang_CT = new mh_banhang_CT(lbel_tencongty.Text, lblcalamviec.Text, iDM_BAN_DAT_BAN_ID);
                    omh_banhang_CT.sBAN_MA = _sMaBan + "";
                    omh_banhang_CT.sPhieu_Ma = Ma_Phieu;
                    if (iDM_BAN_DAT_BAN_ID > 0)
                    {
                        string sSQL = "SELECT dk.THEKHACHHANG FROM DM_BAN_DAT_BAN db INNER JOIN DM_KHACHHANG dk ON db.CUSTOMER_ID = dk.OBJID AND db.DM_BAN_DAT_BAN_ID = " + iDM_BAN_DAT_BAN_ID;
                        DataTable tb = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { sSQL });
                        if (tb.Rows.Count > 0)
                            sMa_The_VIP = tb.Rows[0][0] + "";
                    }
                    omh_banhang_CT.sMaThe_VIP = sMa_The_VIP;
                    omh_banhang_CT.sKhuVucMa = this.GetSelectedValues(gvKhuVuc, "OBJID");

                    //omh_banhang_CT.bDaVaoCa = bDaVaoCa;
                    omh_banhang_CT.ShowInTaskbar = false;
                    omh_banhang_CT.ShowDialog();
                    if (omh_banhang_CT.DialogResult == DialogResult.OK)
                    {
                        this.gridView1_FocusedRowChanged(null, null);
                        this.Client_Server_Send();//2011
                    }
                    else if (omh_banhang_CT.DialogResult == DialogResult.Cancel)
                    {
                        this.DialogResult = DialogResult.OK;
                        this.Dispose();
                    }
                    #endregion
                }
                else
                    this.Label_Click_Lan1(sender, _sMaBan);
            }
        }
        #endregion

        private DataTable getTable_Phieu(string maBan, string maPhieu)
        {
            string sSQL = "";// "SELECT * FROM BH_PHIEU_TMP WHERE DM_BAN_MA LIKE '" + maBan + "'";
            if (maBan != "")
                maBan = " AND P.DM_BAN_MA LIKE '" + maBan + "' ";
            if (maPhieu != "")
                maPhieu = " AND OBJID LIKE '" + maPhieu + "'";

            sSQL = "SELECT b.OBJNAME,p.OBJID, p.DM_BAN_MA, p.NGUOI_LAP, p.NGAY_GIO_VAO, p.NGAY_GIO_RA, " +
                   "        p.TINH_TIEN_THEO_NGAY, p.TIEN_GIO, p.THANH_TIEN, " +
                   "        p.CK_PHANTRAM, p.CK_TIEN, " +
                   "        p.CK_THUCAN_PHANTRAM, p.CK_THUCAN_TIEN, " +//20111108
                   "        p.CK_THUCUONG_PHANTRAM, p.CK_THUCUONG_TIEN, " +//20111108

                   "        p.VAT_PHANTRAM, p.VAT_TIEN, p.TTIEP_PHANTRAM, p.TTIEP_TIEN, " +
                   "        p.PHU_THU_PHANTRAM, p.PHU_THU, p.TONG_TIEN, p.GHI_CHU, " +
                   "        NGAYHH = CONVERT(VARCHAR(30), GETDATE(), 103) +' '+ CONVERT(VARCHAR(30), GETDATE(), 108) " +
                   "FROM BH_PHIEU_TMP p LEFT JOIN DM_BAN b ON p.DM_BAN_MA = b.OBJID " +
                   "WHERE 1 = 1 " + maBan + maPhieu
                ;

            DataTable _tbPhieu = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { sSQL });


            return _tbPhieu;
        }

        #region "   lblTrangChu_Click"
        private void lblTrangChu_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
        #endregion

        #region "   gridView1_FocusedRowChanged"
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (bLoadform)
            {
                string sMaKhuVuc = this.GetSelectedValues(gvKhuVuc, "OBJID");
                if (sMaKhuVuc + "" != "")
                {
                    this.ShowData(sMaKhuVuc);
                    new cpublic().Registry_Set(this.Name + "KHUVUC_DEFAULT", sMaKhuVuc);
                }
            }
        }
        #endregion

        #region "   GetSelectedValues"
        private string GetSelectedValues(DevExpress.XtraGrid.Views.Grid.GridView view, string _tenCot)
        {
            if (view.SelectedRowsCount == 0) return "";

            // iterate cells and compose a tab delimited string of cell values
            for (int i = view.SelectedRowsCount - 1; i >= 0; i--)
            {
                int row = view.GetSelectedRows()[i];
                for (int j = 0; j < view.VisibleColumns.Count; j++)
                {
                    return view.GetDataRow(row)[_tenCot] + "";
                    //result += view.GetRowCellDisplayText(row, view.VisibleColumns[j]);
                }
            }
            return "";
        }
        #endregion

        #region "   1.Add Add_MouseEvent"
        void Add_Event(System.Windows.Forms.Control ctrl)
        {
            ctrl.Click += new EventHandler(Label_Click);
            //ctrl.MouseMove += new MouseEventHandler(pic_MouseDrag);
            //ctrl.MouseDown += new MouseEventHandler(pic_MouseDown);
            //this.loadControl(ctrl);
            new cpublic().loadControl_Format("sodoban" + ctrl.Name, ctrl);
        }

        #endregion

        #region "   Label getLabel"
        #region "   getLabel"
        //Label getLabel1(DataRow _drBan)
        //{
        //    Label lblbanA = new Label();
        //    lblbanA.BackColor = this.getBackColor(_drBan["TRANGTHAI"] + "");
        //    lblbanA.Font = new System.Drawing.Font("Times New Roman", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        //    lblbanA.Location = new System.Drawing.Point(35, 8);
        //    lblbanA.Name = "lblBan" + _drBan["MAKHUVUC"] + _drBan["ban_ma"] + "";
        //    lblbanA.Size = new System.Drawing.Size(100, 100);
        //    lblbanA.TabIndex = 1;

        //    lblbanA.Text = _drBan["ban_ten"] + "";
        //    lblbanA.Tag = _drBan["ban_ma"] + "";
        //    lblbanA.TextAlign = System.Drawing.ContentAlignment.TopCenter;
        //    lblbanA.BorderStyle = BorderStyle.FixedSingle;
        //    this.Add_Event(lblbanA);
        //    //

        //    lblbanA.Controls.Add(this.getLabel_Top(lblbanA, _drBan));

        //    lblbanA.Controls.Add(this.getLabel_Bottom(lblbanA, _drBan, tb));
        //    lblbanA.Cursor = Cursors.Hand;//#

        //    return lblbanA;
        //}
        #endregion

        #region "   getPanel"
        Panel getPanel(DataRow _drBan, Boolean iKeo_Tha_Ban, Boolean iHienThi_SoKhach, Boolean iHienThi_TongTien)
        {
            Panel pnlbanA = new Panel();
            pnlbanA.BackColor = this.getBackColor(_drBan["TRANGTHAI"] + "");
            pnlbanA.Font = new System.Drawing.Font("Times New Roman", 12.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            pnlbanA.Location = new System.Drawing.Point(35, 8);
            pnlbanA.Name = "lblBan" + _drBan["MAKHUVUC"] + _drBan["ban_ma"] + "";
            pnlbanA.Size = new System.Drawing.Size(100, 100);
            pnlbanA.TabIndex = 1;
            pnlbanA.Text = _drBan["ban_ten"] + "";
            pnlbanA.Tag = _drBan["ban_ma"] + "";

            pnlbanA.BackgroundImageLayout = ImageLayout.Stretch;
            this.Add_Event(pnlbanA);
            //
            pnlbanA.Controls.Add(this.getLabel_Top(pnlbanA, _drBan, iKeo_Tha_Ban, iHienThi_SoKhach));
            pnlbanA.Controls.Add(this.getLabel_Bottom(pnlbanA, _drBan, tb, iKeo_Tha_Ban,iHienThi_TongTien));
            pnlbanA.Cursor = Cursors.Hand;//#
            return pnlbanA;
        }
        #endregion

        #region "   getLabel_Top"
        Label getLabel_Top(System.Windows.Forms.Control ParentControl, DataRow _drBan, Boolean iKeo_Tha_Ban, Boolean iHienThi_SoKhach)
        {
            Label lblbanA_tmp = new Label();
            lblbanA_tmp.BackColor = System.Drawing.Color.Transparent;//.BackColor = ParentControl.BackColor;
            lblbanA_tmp.Font = new System.Drawing.Font(ParentControl.Font.Name, ParentControl.Font.Size, ParentControl.Font.Style, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            if (ParentControl.Region == null)
                lblbanA_tmp.Location = new System.Drawing.Point(-1, -1);
            else
                lblbanA_tmp.Location = new System.Drawing.Point(-1, 5);
            lblbanA_tmp.ForeColor = ParentControl.ForeColor;

            lblbanA_tmp.Name = "lblBan" + _drBan["MAKHUVUC"] + _drBan["ban_ma"] + "_top";
            if (ParentControl.Region == null)
                lblbanA_tmp.Size = new System.Drawing.Size(ParentControl.Width, ParentControl.Height / 3);
            else
                lblbanA_tmp.Size = new System.Drawing.Size(ParentControl.Width, ParentControl.Height / 3 - 8);

            lblbanA_tmp.TabIndex = 1;

            lblbanA_tmp.Text = _drBan["ban_ten"] + "";

            lblbanA_tmp.Tag = ParentControl.Tag;
            if (ParentControl.Region == null)
                lblbanA_tmp.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            else
                lblbanA_tmp.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
            lblbanA_tmp.BorderStyle = BorderStyle.None;
            this.Add_Event(lblbanA_tmp);
            lblbanA_tmp.Cursor = Cursors.Hand;//#
            //
            bColor = lblbanA_tmp.BackColor;
            if (iKeo_Tha_Ban)
                this.Add_Event_ChuyenBan(lblbanA_tmp);
            return lblbanA_tmp;
        }
        #endregion

        #region "   getLabel_Bottom"
        Label getLabel_Bottom(System.Windows.Forms.Control ParentControl, DataRow _drBan, DataTable tb, Boolean iKeo_Tha_Ban, Boolean iHienThi_TongTien)
        {
            Label lblbanA_tmp = new Label();
            lblbanA_tmp.BackColor = System.Drawing.Color.Transparent;//.BackColor = ParentControl.BackColor;            
            lblbanA_tmp.Font = new System.Drawing.Font(ParentControl.Font.Name, 10, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            lblbanA_tmp.Location = new System.Drawing.Point(-1, ParentControl.Height / 3);
            lblbanA_tmp.ForeColor = ParentControl.ForeColor;

            lblbanA_tmp.Name = "lblBan" + _drBan["MAKHUVUC"] + _drBan["ban_ma"] + "_bottom";
            lblbanA_tmp.Size = new System.Drawing.Size(ParentControl.Width, ParentControl.Height * 2 / 3);


            lblbanA_tmp.TabIndex = 1;
            //if (_drBan["TRANGTHAI"] + "" == "1")
            //    lblbanA_tmp.Text = "(" + _drBan["LOAIDICHVU_TEN"] + ")\n" + _drBan["GIO_VAO"] + "";
            //else
            //    lblbanA_tmp.Text = "(" + _drBan["LOAIDICHVU_TEN"] + ")\n" + _drBan["TRANGTHAI_TEN"] + "";

            // tohoai hien thi chu "Ca phê" tren ban
            // lblbanA_tmp.Text = "(" + _drBan["LOAIDICHVU_TEN"] + ")\n" + _drBan["TRANGTHAI_TEN"] + "";
            if (tb.Rows.Count > 0 && Convert.ToBoolean(tb.Rows[0]["LOAI_DICH_VU"] + "") == true)
                lblbanA_tmp.Text = "(" + _drBan["LOAIDICHVU_TEN"] + ")\n" + _drBan["TRANGTHAI_TEN"] + "";
            else
                lblbanA_tmp.Text = _drBan["TRANGTHAI_TEN"] + "";


            lblbanA_tmp.Tag = ParentControl.Tag;
            lblbanA_tmp.TextAlign = System.Drawing.ContentAlignment.TopCenter;
            lblbanA_tmp.BorderStyle = BorderStyle.None;
            this.Add_Event(lblbanA_tmp);
            lblbanA_tmp.Cursor = Cursors.Hand;
            //
            if (iKeo_Tha_Ban)
                this.Add_Event_ChuyenBan(lblbanA_tmp);
            return lblbanA_tmp;
        }
        #endregion

        void Add_Event_ChuyenBan(System.Windows.Forms.Control ctrl)
        {
            ctrl.AllowDrop = true;
            ctrl.MouseDown += new MouseEventHandler(Label_MouseDown);
            ctrl.MouseMove += new MouseEventHandler(Label_MouseMove);
            ctrl.GiveFeedback += new GiveFeedbackEventHandler(Label_GiveFeedback);
            //
            ctrl.DragDrop += new DragEventHandler(label_DragDrop);
            ctrl.DragLeave += new EventHandler(label_DragLeave);
            ctrl.DragEnter += new DragEventHandler(label_DragEnter);
        }
        #endregion

        #region "   getBackColor"
        Color getBackColor(string _TrangThai)
        {
            //if (_TrangThai == "0")//Chưa có khách
            return Color.White;
            //else if (_TrangThai == "1")//Có khách
            //    return Color.SpringGreen;
            //else //if (_TrangThai == "2")//'Đã đặt trước
            //    return Color.Yellow;
        }
        #endregion

        #region "   lbl_Click"
        #region "   lblVaoCa_Click"
        private void lblVaoCa_Click(object sender, EventArgs e)
        {
            //if (Variable.username == "")
            //{
            //    lblVaoCa.Text = "Vào Ca";
            //    lblcalamviec.Text = "CA LÀM VIỆC";
            //}
            //else
            //{
            this.LoadCaLamViec();
            //}
        }
        void LoadCaLamViec()
        {
            DataTable tbCalamviec = new thuvien().SP_SelectDataTable("sp_DM_DANGNHAP",
                                                                    new string[] { "@flag" },
                                                                    new object[] { 5 });
            if (tbCalamviec.Rows.Count >= 1)
            {
                lblVaoCa.Text = "Ra\nCa";
                lblcalamviec.Text = tbCalamviec.Rows[0]["OBJNAME"] + "";
            }
            else
                lblcalamviec.Text = "";
        }
        #endregion

        #region "   lblTachGopBan_Click"
        private void lblTachGopBan_Click(object sender, EventArgs e)
        {
            if (sender != null)
            if (((System.Windows.Forms.Control)sender).Text == "") return;
            if (Variable.username == "") return;
            if (ochon == chon.Tach_Gop_Ban)
                this.setNoneMesssage();
            else
            {
                switch (str_lang)
                {
                    case "vi-VN":
                        lblMessage_sodoban.Text = "Chọn bàn cần tách/gộp";
                        break;
                    case "en-US":
                        lblMessage_sodoban.Text = "Choose table to Split/ Merge";
                        break;
                }

                //lblMessage_sodoban.Text = "Chọn bàn cần tách/gộp";
                ochon = chon.Tach_Gop_Ban;
            }
        }
        #endregion

        #region "   lblTachGopPhieu_Click"
        private void lblTachGopPhieu_Click(object sender, EventArgs e)
        {
            if (sender != null)
            if (((System.Windows.Forms.Control)sender).Text == "") return;
            if (Variable.username == "") return;
            if (ochon == chon.Tach_Gop_Phieu)
                this.setNoneMesssage();
            else
            {
                switch (str_lang)
                {
                    case "vi-VN":
                        lblMessage_sodoban.Text = "Chọn bàn cần tách/gộp phiếu";
                        break;
                    case "en-US":
                        lblMessage_sodoban.Text = "Choose table to Split/ Merge bills";
                        break;
                }
                //lblMessage_sodoban.Text = "Chọn bàn cần tách/gộp phiếu";
                ochon = chon.Tach_Gop_Phieu;
            }
        }
        #endregion

        #region "   lblChuyenBan_Click"
        private void lblChuyenBan_Click(object sender, EventArgs e)
        {
            if (sender != null)
                if (((System.Windows.Forms.Control)sender).Text == "") return;
            if (Variable.username == "") return;
            if (ochon == chon.Chuyen_Ban)
                this.setNoneMesssage();
            else
            {
                switch (str_lang)
                {
                    case "vi-VN":
                        lblMessage_sodoban.Text = "Chọn bàn cần chuyển";
                        break;
                    case "en-US":
                        lblMessage_sodoban.Text = "Choose table to move";
                        break;
                }
               // lblMessage_sodoban.Text = "Chọn bàn cần chuyển";
                ochon = chon.Chuyen_Ban;
            }
        }
        #endregion

        #region "   lblInLaiHoaDon_Click"
        private void lblInLaiHoaDon_Click(object sender, EventArgs e)
        {
            if (sender != null)
            if (((System.Windows.Forms.Control)sender).Text == "") return;
            if (Variable.username == "") return;
            lblMessage_sodoban.Text = "";
            string maKhuVuc = "";
            DataRow dr = gvKhuVuc.GetDataRow(gvKhuVuc.FocusedRowHandle);
            if (dr != null)
                maKhuVuc = dr["OBJID"] + "";
            new Print_InLai_HoaDon(maKhuVuc).ShowDialog();
        }
        #endregion

        #region "   lblInHoaDon_Click"
        private void lblInHoaDon_Click(object sender, EventArgs e)
        {
            if (sender != null)
            if (((System.Windows.Forms.Control)sender).Text == "") return;
            if (Variable.username == "") return;
            if (ochon == chon.In_Hoa_Don)//2011
                this.setNoneMesssage();
            else
            {
                lblMessage_sodoban.Text = "Chọn bàn in Hóa Đơn";
                ochon = chon.In_Hoa_Don;
            }
        }
        #endregion

        #region "   lblKhachhang_Click"
        private void lblKhachhang_Click(object sender, EventArgs e)
        {
            if (sender != null)
            if (((System.Windows.Forms.Control)sender).Text == "") return;
            if (Variable.username == "") return;
            if (ochon == chon.Khach_Hang)
            {
                this.setNoneMesssage();
            }
            else
            {
                lblMessage_sodoban.Text = lblKhachhang_sodoban.Text;
                ochon = chon.Khach_Hang;
            }
        }
        #endregion

        #region "   lblMoKet_Click"
        private void lblMoKet_Click(object sender, EventArgs e)
        {
            if (sender != null)
            if (((System.Windows.Forms.Control)sender).Text == "") return;
            //if (Variable.username == "") return;
            //lblMessage.Text= lblMoKet.Text;

            if (Variable.username == "") return;
            if (ochon == chon.The_Khach_Hang)
            {
                this.setNoneMesssage();
            }
            else
            {
                lblMessage_sodoban.Text = lblMoKet_sodoban.Text;
                ochon = chon.The_Khach_Hang;
            }

        }
        #endregion
        #endregion

        #region "   setNoneMesssage"
        void setNoneMesssage()
        {
            ochon = chon.None;
            lblMessage_sodoban.Text = "";
        }
        #endregion

        #region "   Label_Click_Lan1"
        void Label_Click_Lan1(object sender, string _ban_ma)
        {
            if (_ban_ma != "" && Variable.username != "")
            {
                string sTrangThaiBan = "1";
                string sSQL = "SELECT TRANGTHAI FROM DM_BAN WHERE OBJID = " + _ban_ma;
                DataTable tbTMP = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new string[] { sSQL });
                if (tbTMP.Rows.Count > 0)
                {
                    sTrangThaiBan = tbTMP.Rows[0]["TRANGTHAI"] + "";
                    //0	Chưa có khách	NULL
                    //1	Có khách	NULL
                    //2	Đã đặt trước	NULL
                }

                //DataTable tb = new thuvien().SP_SelectDataTable("",
                if (ochon == chon.Tach_Gop_Ban && sTrangThaiBan != "0")
                {
                    #region "   chon.Tach_Gop_Ban"
                    mh_banhang1_TachGopBan omh_banhang1_TachGopBan = new mh_banhang1_TachGopBan(_ban_ma, Variable.ngay_gio_hienhanh);
                    omh_banhang1_TachGopBan.ShowDialog();
                    if (omh_banhang1_TachGopBan.DialogResult == DialogResult.OK)
                    {
                        this.gridView1_FocusedRowChanged(null, null);
                        this.Client_Server_Send();//2011
                    }
                    this.lblTachGopBan_Click(null, null);
                    #endregion
                }
                else if (ochon == chon.Tach_Gop_Phieu && sTrangThaiBan != "0")
                {
                    #region "   chon.Tach_Gop_Phieu"
                    mh_banhang2_TachGopPhieu omh_banhang2_TachGopPhieu = new mh_banhang2_TachGopPhieu(_ban_ma);
                    omh_banhang2_TachGopPhieu.ShowDialog();
                    if (omh_banhang2_TachGopPhieu.DialogResult == DialogResult.OK)
                    {
                        this.gridView1_FocusedRowChanged(null, null);
                        this.Client_Server_Send();//2011
                    }
                    this.lblTachGopPhieu_Click(null, null);
                    #endregion
                }
                else if (ochon == chon.Chuyen_Ban && sTrangThaiBan != "0")
                {
                    #region "   chon.Chuyen_Ban"
                    mh_banhang3_ChuyenBan omh_banhang3_ChuyenBan = new mh_banhang3_ChuyenBan(_ban_ma, Variable.ngay_gio_hienhanh);
                    omh_banhang3_ChuyenBan.ShowDialog();
                    if (omh_banhang3_ChuyenBan.DialogResult == DialogResult.OK)
                    {
                        this.gridView1_FocusedRowChanged(null, null);
                        this.Client_Server_Send();//2011
                    }
                    this.lblChuyenBan_Click(null, null);
                    #endregion
                }
                else if (ochon == chon.In_Hoa_Don)
                {
                    this.setNoneMesssage();
                    #region "   chon.In_Hoa_Don"
                    if (Variable.arrDM_MAYIN_HD == null)
                        new Variable().Get_DM_MAYIN_HD();
                    cpublic ocpublic = new cpublic();
                    //Mo cong com                   
                    DataTable _tbPhieu = this.getTable_Phieu(Control_Current.Tag + "", "");
                    string maPhieu = "";
                    if (_tbPhieu.Rows.Count == 2)
                    {
                        mh_banhang_CT_InPhieu omh_banhang_CT_InPhieu = new mh_banhang_CT_InPhieu(Control_Current.Tag + "");
                        maPhieu = omh_banhang_CT_InPhieu.ShowForm();
                        if (omh_banhang_CT_InPhieu.DialogResult == DialogResult.Cancel)
                            goto khong_in;
                    }
                    else if (_tbPhieu.Rows.Count == 1)
                        maPhieu = _tbPhieu.Rows[0]["OBJID"] + "";

                    if (maPhieu != "")
                    {
                        //Boolean bShare_May_In_hoadon = ocpublic.Registry_Get("SHARE_ELLIX21") + "" == "True";
                        //Boolean bIn_Tai_MayKhac = ocpublic.Registry_Get("SHARE_ELLIX22") + "" == "True";
                        //if (bShare_May_In_hoadon && bIn_Tai_MayKhac)
                        //{
                        //    string IPMay_Nhan_DuLieu = ocpublic.Registry_Get("SHARE_ELLIX23") + "";
                        //    int sPort_May_Nhan_DuLieu = 8888;//int.Parse("0" + ocpublic.Registry_Get("SHARE_ELLIX24"));

                        //    ocpublic.Send_DuLieu_Den_MayInCOM("hoadon", "abc", "1\r\n" + maPhieu + "", IPMay_Nhan_DuLieu, sPort_May_Nhan_DuLieu);
                        //}
                        //else
                        {

                            DataTable tb = new thuvien().SP_SelectDataTable("sp_DM_MAYIN_HD", null, null);
                            DataView dv = tb.DefaultView;
                            //dv.Sort = "COMNAME";
                            //int vitri = dv.Find(new object[] { "USB" });
                            //

                            int iPrintOut = 0;
                            if (tb.Rows.Count > 0)
                                int.TryParse(tb.Rows[0]["PrintOut"] + "", out iPrintOut);

                            #region "   sTieuDe - sFooter"
                            string sFooter = "";
                            string sTieuDe = "HÓA ĐƠN BÁN HÀNG";
                            DataTable tb_DM_MAYIN_HD_CAUHINH = new thuvien().SP_SelectDataTable("sp_DM_MAYIN_HD_CAUHINH", new string[] { "@flag" }, new object[] { 4 });
                            if (tb_DM_MAYIN_HD_CAUHINH.Rows.Count > 0)
                            {
                                sFooter = tb_DM_MAYIN_HD_CAUHINH.Rows[0]["FOOTER"] + "";
                                sTieuDe = tb_DM_MAYIN_HD_CAUHINH.Rows[0]["TITLE"] + "";
                            }
                            #endregion

                            for (int ip = 1; ip <= iPrintOut; ip++)
                            {
                                dv.Sort = "COMNAME";
                                int vitri = dv.Find(new object[] { "USB" });
                                int vitri_A5 = dv.Find(new object[] { "A5" });
                                int vitri_IN_KIM = dv.Find(new object[] { "IN KIM" });
                                int vitri_bixolon = dv.Find(new object[] { "BIXOLON" });
                                int vitri_bixolon100 = dv.Find(new object[] { "BIXOLON100" });
                                if (vitri > -1 ||
                                    vitri_bixolon > -1)
                                {
                                    if (vitri > -1)
                                    {
                                        LPV_POS.mh_pos.mh_inbaocao.mh_viewhoadon mh = new LPV_POS.mh_pos.mh_inbaocao.mh_viewhoadon();
                                        mh.InBill(maPhieu, 1, sTieuDe, iPrintOut);
                                    }
                                    else
                                    {

                                        LPV_POS.mh_pos.mh_inbaocao.mh_viewhoadon mh = new LPV_POS.mh_pos.mh_inbaocao.mh_viewhoadon();
                                        mh.InBill(maPhieu, 2, sTieuDe, iPrintOut);
                                    }
                                    goto khong_in;
                                }
                                else if (vitri_A5 > -1)
                                {
                                    LPV_POS.mh_pos.mh_inbaocao.mh_inA5 mh = new LPV_POS.mh_pos.mh_inbaocao.mh_inA5();
                                    mh.f_inhoadon(Control_Current.Tag + "", maPhieu, iDM_BAN_DAT_BAN_ID, false, iPrintOut, sTieuDe, sFooter, false);
                                    goto khong_in;
                                }
                                else if (vitri_bixolon100 > -1)
                                {
                                    //LPV_POS.mh_pos.mh_inbaocao.mh_inBixolon100 mh = new LPV_POS.mh_pos.mh_inbaocao.mh_inBixolon100();
                                    //mh.f_inhoadon(Control_Current.Tag + "", maPhieu, iDM_BAN_DAT_BAN_ID, false, iPrintOut);
                                    LPV_POS.mh_pos.mh_inbaocao.mh_viewhoadon mh = new LPV_POS.mh_pos.mh_inbaocao.mh_viewhoadon();
                                    mh.InBill(maPhieu, 3, sTieuDe, iPrintOut);
                                    goto khong_in;
                                }
                                else if (vitri_IN_KIM > -1)
                                {
                                    LPV_POS.mh_pos.mh_inbaocao.mh_in_KIM mh = new LPV_POS.mh_pos.mh_inbaocao.mh_in_KIM();
                                    mh.f_inhoadon(Control_Current.Tag + "", maPhieu, iDM_BAN_DAT_BAN_ID, false, sTieuDe);
                                }
                                else
                                {
                                    Boolean bShare_May_In_hoadon = ocpublic.Registry_Get("SHARE_ELLIX21") + "" == "True";
                                    Boolean bIn_Tai_MayKhac = ocpublic.Registry_Get("SHARE_ELLIX22") + "" == "True";
                                    if (bShare_May_In_hoadon && bIn_Tai_MayKhac)
                                    {
                                        string IPMay_Nhan_DuLieu = ocpublic.Registry_Get("SHARE_ELLIX23") + "";
                                        int sPort_May_Nhan_DuLieu = 8888;//int.Parse("0" + ocpublic.Registry_Get("SHARE_ELLIX24"));

                                        ocpublic.Send_DuLieu_Den_MayInCOM("hoadon", "abc", "1\r\n" + maPhieu + "", IPMay_Nhan_DuLieu, sPort_May_Nhan_DuLieu);
                                    }
                                    else
                                        new print_BAN_HANG().Print_PHIEU_BANHANG(maPhieu, false);
                                }
                            }
                        }
                    }
                khong_in:
                    ochon = chon.In_Hoa_Don;
                    this.lblInHoaDon_Click(null, null);
                    #endregion
                }
                else if (ochon == chon.Dat_Ban)
                {
                    #region "   chon.Dat_Ban -- ko xai"
                    //thuvien othuvien = new thuvien();
                    //DataTable tbDM_Ban = othuvien.SP_SelectDataTable("SP_EXECUTESQL",
                    //                                                    new string[] { "@sSQL" },
                    //                                                    new object[] { "SELECT * FROM DM_BAN WHERE OBJID LIKE '" + _ban_ma + "'" });
                    //if (tbDM_Ban.Rows.Count > 0)
                    //{
                    //    string sghichu = tbDM_Ban.Rows[0]["GHICHU"] + "";
                    //    string strangthai = tbDM_Ban.Rows[0]["TRANGTHAI"] + "";
                    //    //if (strangthai == "0" || //BAN TRONG
                    //    //    strangthai == "2")//BAN DANG CO NGUOI DAT
                    //    {
                    //        //mh_chu omh_chu = new mh_chu();
                    //        //string sSQL = "";
                    //        //string str = omh_chu.ShowForm(sghichu, 200, 200, false);
                    //        //if (omh_chu.DialogResult == DialogResult.OK)
                    //        //{
                    //        //    if (str.Trim() == "")
                    //        //    {
                    //        //        sSQL = "UPDATE DM_BAN SET TRANGTHAI = 0, GHICHU ='' WHERE OBJID LIKE '" + _ban_ma + "'";
                    //        //    }
                    //        //    else
                    //        //    {
                    //        //        sSQL = "UPDATE DM_BAN SET TRANGTHAI = 2, GHICHU =N'" + str + "' WHERE OBJID LIKE '" + _ban_ma + "'";
                    //        //    }
                    //        //    int irt = othuvien.SP_Update("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { sSQL });

                    //        //    this.gridView1_FocusedRowChanged(null, null);
                    //        //}
                    //        frmDM_BAN_DAT_BAN ofrmDM_BAN_DAT_BAN = new frmDM_BAN_DAT_BAN();
                    //        ofrmDM_BAN_DAT_BAN.sDM_BAN_ID = _ban_ma;
                    //        ofrmDM_BAN_DAT_BAN.ShowDialog();
                    //        if (ofrmDM_BAN_DAT_BAN.DialogResult == DialogResult.OK)
                    //            this.gridView1_FocusedRowChanged(null, null);
                    //    }
                    //    //else// if (strangthai == "2")
                    //    //    new mh_thongbao("Không thể đặt bàn tại bàn này", 2).ShowDialog();
                    //}
                    //else
                    //    new mh_thongbao("Không thể đặt bàn tại bàn này", 2).ShowDialog();
                    //this.lblDatBan_Click(null, null);
                    #endregion

                    #region "   chon.Dat_Ban"
                    iDM_BAN_DAT_BAN_ID = -1;
                    this.lblDatBan_Click(null, null);
                    thuvien othuvien = new thuvien();
                    DataTable tbDM_Ban = othuvien.SP_SelectDataTable("SP_EXECUTESQL",
                                                                        new string[] { "@sSQL" },
                                                                        new object[] { "SELECT * FROM DM_BAN WHERE OBJID LIKE '" + _ban_ma + "'" });
                    if (tbDM_Ban.Rows.Count > 0)
                    {
                        string sghichu = tbDM_Ban.Rows[0]["GHICHU"] + "";
                        string strangthai = tbDM_Ban.Rows[0]["TRANGTHAI"] + "";

                        frmDM_BAN_DAT_BAN ofrmDM_BAN_DAT_BAN = new frmDM_BAN_DAT_BAN();
                        ofrmDM_BAN_DAT_BAN.sDM_BAN_ID = _ban_ma;
                        iDM_BAN_DAT_BAN_ID = ofrmDM_BAN_DAT_BAN.ShowForm();
                        this.gridView1_FocusedRowChanged(null, null);
                        if (ofrmDM_BAN_DAT_BAN.DialogResult == DialogResult.OK)//9999
                        {
                            this.Label_Click(sender, null);
                            this.Client_Server_Send();//2011
                        }
                        iDM_BAN_DAT_BAN_ID = -1;
                    }
                    else
                        new mh_thongbao("Không thể đặt bàn tại bàn này", 2).ShowDialog();
                    #endregion
                }
                else if (ochon == chon.Dat_Ban_Huy)
                {
                    #region "   chon.Dat_Ban"
                    thuvien othuvien = new thuvien();
                    sSQL = "SELECT b.TRANGTHAI, b.GHICHU " +
                          "FROM DM_BAN b " +
                          "     INNER JOIN DM_BAN_DAT_BAN db ON db.DM_BAN_ID = b.OBJID " +
                          "                                     AND db.ISDELETE = CAST(0 AS BIT) " +
                          "                                     AND b.OBJID LIKE '" + _ban_ma + "'";

                    DataTable tbDM_Ban = othuvien.SP_SelectDataTable("SP_EXECUTESQL",
                                                                        new string[] { "@sSQL" },
                                                                        new object[] { sSQL });
                    if (tbDM_Ban.Rows.Count > 0)
                    {
                        string sghichu = tbDM_Ban.Rows[0]["GHICHU"] + "";
                        string strangthai = tbDM_Ban.Rows[0]["TRANGTHAI"] + "";
                        if (strangthai == "2" || strangthai == "1")
                        {

                            //if (new mh_thongbao("Bạn muốn hủy đặt bàn?", 3).ShowForm() == DialogResult.OK)
                            if (MessageBox_LPV.Show("Bạn muốn hủy đặt bàn?", MessageBox_LPV.chon.OkCancel) == DialogResult.OK)
                            {
                                othuvien.SP_Update("sp_DM_BAN_DAT_BAN",
                                                    new string[] { "@flag", "@DM_BAN_ID" },
                                                    new object[] { 3, _ban_ma });

                                this.gridView1_FocusedRowChanged(null, null);
                                this.Client_Server_Send();//2011
                            }
                        }
                    }
                    this.lblDatBan_Huy_Click(null, null);
                    #endregion
                }
            }
        }
        #endregion

        void Client_Server_Send()
        {
            cpublic ocpublic = new cpublic();
            if (ocpublic.Registry_Get("POSMayTram") + "" == "True")
            {//neu la may CLIENT
                string sTCP_IP = ocpublic.Registry_Get("POSMayChu_TCP_IP") + "";
                if (sTCP_IP != "")
                {
                    int sPort_May_Nhan_DuLieu = 7777;
                    string sMaKhuVuc = this.GetSelectedValues(gvKhuVuc, "OBJID");
                    ocpublic.Send_DuLieu_Den_MayInCOM(sMaKhuVuc, sTCP_IP, sPort_May_Nhan_DuLieu);
                }
            }
        }
        #region "   timer1_Tick"
        private void timer1_Tick(object sender, EventArgs e)
        { 
          
            if (sMAKHUVUC_static != "")
            {
                string sMaKhuVuc = this.GetSelectedValues(gvKhuVuc, "OBJID");
                if (sMaKhuVuc == sMAKHUVUC_static)//KV client gui den = KV dang dc chon
                    this.ShowData(sMaKhuVuc);
                sMAKHUVUC_static = "";
            }
            if (Button.MouseButtons != MouseButtons.Left)
            {
                this.Cursor = Cursors.Default;
            }
            if (bLoadform)
            {
                try
                {
                    //if (timer1.Tag + "" != "")
                    {
                        lbel_ngayhienhanh.Text = Variable.ngay_gio_hienhanh.ToString("dd/MM/yyyy") + "(" + this.V2E(Variable.ngay_gio_hienhanh.DayOfWeek + "") + ")\n";
                        lbel_ngayhienhanh.Text += Variable.ngay_gio_hienhanh.ToString("HH:mm:ss");

                        lblVaoCa.ForeColor = Color.Black;
                        if (Variable.username == "")
                        {
                            lblVaoCa.BackColor = this.RandomColor(0, 255);

                            lblVaoCa.ForeColor = this.RandomColor(0, 200);

                        }
                        else
                            lblVaoCa.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
                        if (lblMessage_sodoban.Text != "")
                            lblMessage_sodoban.ForeColor = this.RandomColor(0, 255);
                    }
                }
                catch (Exception ex)
                {
                    timer1.Tag = Variable.ngay_gio_hienhanh;
                    string s = ex.Message;
                }
            }
        }
        Color RandomColor(int iRandomLimit1, int iRandomLimit2)
        {
            Random lRandom = new Random();
            int chiSoMau1 = lRandom.Next(iRandomLimit1, iRandomLimit2);
            int chiSoMau2 = lRandom.Next(iRandomLimit1, iRandomLimit2);//100, 150
            int chiSoMau3 = lRandom.Next(iRandomLimit1, iRandomLimit2);//0, 50
            if (iRandomLimit2 < 250)
            {
                chiSoMau1 = lRandom.Next(255);
                chiSoMau2 = lRandom.Next(255);//100, 150
                chiSoMau3 = lRandom.Next(255);//0, 50
            }
            return Color.FromArgb(chiSoMau1, chiSoMau2, chiSoMau3);
        }
        #endregion

        #region "   V2E"
        string V2E(string dayofWeek)
        {
            return dayofWeek.Replace("Monday", "T2").Replace("Tuesday", "T3").Replace("Wednesday", "T4").Replace("Thursday", "T5").Replace("Friday", "T6").Replace("Saturday", "T7").Replace("Sunday", "CN");
        }
        #endregion

        private void lblcalamviec_Click(object sender, EventArgs e)
        {

        }

        #region ---------------begin IN BILL TINH DIEM KHACH HANG---------------
        //private Boolean Print_PHIEU_BANHANG(string _maPhieu)
        //{
        //    #region "   chon.In_Hoa_Don"

        //    if (Variable.arrDM_MAYIN_HD == null)
        //    {
        //        Variable.Get_DM_MAYIN_HD();
        //    }
        //    //Mo cong com
        //    DataRow _drPhieu = null;
        //    DataTable _tbPhieuCT = null;
        //    DataTable _tbPhieu = this.getTable_Phieu("", _maPhieu + "");
        //    string maPhieu = "";
        //    if (_tbPhieu.Rows.Count == 1)
        //        maPhieu = _tbPhieu.Rows[0]["OBJID"] + "";
        //    else
        //        return false;
        //    if (_tbPhieu.Select("OBJID LIKE '" + maPhieu + "'").Length > 0)
        //        _drPhieu = _tbPhieu.Select("OBJID LIKE '" + maPhieu + "'")[0];
        //    string sSQL = "";// "SELECT OBJNAME = (CASE b.MAHH WHEN 'Tien_Gio' THEN N'Tiền giờ' ELSE h.OBJNAME END ), b.* FROM BH_PHIEU_CT_TMP b LEFT JOIN DM_HH h ON b.MAHH = h.OBJID WHERE b.BH_PHIEU_MA LIKE '" + maPhieu + "' ORDER BY b.OBJID";
        //    sSQL =
        //        "SELECT MIN(aa.OBJID), aa.OBJNAME, aa.BH_PHIEU_MA, aa.MAHH, SO_LUONG = SUM(aa.SO_LUONG), aa.DVT, DON_GIA = MAX(aa.DON_GIA), " +
        //        "       CHIETKHAU_PHANTRAM = MAX(aa.CHIETKHAU_PHANTRAM), CHIETKHAU_TIEN = MAX(aa.CHIETKHAU_TIEN), THANH_TIEN = SUM(aa.THANH_TIEN)  " +
        //        "FROM  " +
        //        "(  " +
        //        "    SELECT b.OBJID, OBJNAME = (CASE b.MAHH WHEN 'Tien_Gio' THEN N'Tiền giờ' ELSE h.OBJNAME END ), b.BH_PHIEU_MA, " +
        //        "           b.MAHH, b.SO_LUONG, b.DVT, b.DON_GIA, b.CHIETKHAU_PHANTRAM, " +
        //        "           b.CHIETKHAU_TIEN, b.THANH_TIEN " +
        //        "    FROM BH_PHIEU_CT_TMP b " +
        //        "        LEFT JOIN DM_HH h ON b.MAHH = h.OBJID  " +
        //        "    WHERE b.BH_PHIEU_MA LIKE '101000011'  " +
        //        ")aa " +
        //        "GROUP BY aa.OBJNAME, aa.BH_PHIEU_MA, aa.MAHH, aa.DVT   " +
        //        "HAVING SUM(aa.SO_LUONG) > 0 " +
        //        "ORDER BY MIN(aa.OBJID)";

        //    _tbPhieuCT = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { sSQL });

        //    if (_drPhieu != null)
        //    {
        //        int intLoop = 0; //So máy in
        //        for (intLoop = 0; intLoop < Variable.arrDM_MAYIN_HD.Length; intLoop++)
        //        {
        //            //mở cổng COM
        //            if (Variable.arrDM_MAYIN_HD[intLoop]["KIND"] + "" == "0" || Variable.arrDM_MAYIN_HD[intLoop]["KIND"] + "" == "1" || Variable.arrDM_MAYIN_HD[intLoop]["KIND"] + "" == "2")
        //                if (Variable.gsrlCOMBillport == null)
        //                    Variable.SerialPort_Open();
        //            if (Variable.arrDM_MAYIN_HD[intLoop]["KIND"] + "" == "0") //in cổng COM K80
        //                this.Print_PHIEU_BANHANG(Variable.gsrlCOMBillport[intLoop], _drPhieu, _tbPhieuCT);
        //            else if (Variable.arrDM_MAYIN_HD[intLoop]["KIND"] + "" == "2") //in cổng COM K58
        //            {

        //            }
        //        }
        //    }
        //    Variable.SerialPort_Close();
        //    return true;
        //    #endregion
        //}

        //private void Print_PHIEU_BANHANG(System.IO.Ports.SerialPort psrlCOMport, DataRow _drPhieu, DataTable _tbPhieuCT)
        //{
        //    #region "   Print_PHIEU_BANHANG"
        //    try
        //    {
        //        #region "   KHAI BAO BIEN..."
        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        string Print_Align_Center = ((char)(27)).ToString() + ((char)(97)).ToString() + ((char)(1)).ToString();
        //        string Print_Double_Height = ((char)(27)).ToString() + ((char)(33)).ToString() + ((char)(16)).ToString();
        //        string Print_Align_Left = ((char)(27)).ToString() + ((char)(97)).ToString() + '\0';
        //        string Print_Font_Normal_40CharPerRow = ((char)(27)).ToString() + ((char)(33)).ToString() + ((char)(1)).ToString();

        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        cpublic ocpublic = new cpublic();
        //        string sTenQuan = "";
        //        string sDiaChi = "";
        //        string sSoDienThoai = "";
        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        DataTable tbSETPARA = null;
        //        #endregion

        //        #region "   tbSETPARA -- TIEU_DE cty, DIA_CHI"
        //        string sSQL = "SELECT * FROM SETPARA";
        //        tbSETPARA = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { sSQL });

        //        if (tbSETPARA.Rows.Count > 0)
        //        {
        //            sTenQuan = tbSETPARA.Rows[0]["LEFTTOPLINE1"] + "";
        //            sDiaChi = tbSETPARA.Rows[0]["LEFTTOPLINE2"] + "";
        //            sSoDienThoai = tbSETPARA.Rows[0]["ORGTEL"] + "";
        //            if (sSoDienThoai != "")
        //                sSoDienThoai = "Tel: " + sSoDienThoai;
        //        }
        //        #endregion

        //        #region "   TEN QUAN"
        //        //////////////////////////////TEN QUAN
        //        psrlCOMport.Write(Print_Align_Center);
        //        psrlCOMport.Write(Print_Double_Height);
        //        if (sTenQuan != "")
        //            psrlCOMport.WriteLine(ocpublic.RemoveSign4VietnameseString(sTenQuan.Trim(' ')));
        //        psrlCOMport.WriteLine("");

        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 


        //        psrlCOMport.Write(Print_Align_Left);
        //        psrlCOMport.Write(Print_Font_Normal_40CharPerRow); //in chữ thường 40chữ/dòng]
        //        #endregion

        //        #region "   DIA CHI QUÁN"
        //        ///////////////////////////////DIA CHI QUÁN
        //        if (sDiaChi != "")
        //            psrlCOMport.WriteLine(ocpublic.RemoveSign4VietnameseString(sDiaChi.Trim(' ')));
        //        #endregion

        //        #region "   SO DIEN THOAI"
        //        ///////////////////////////////SO DIEN THOAI
        //        if (sSoDienThoai != "")
        //            psrlCOMport.WriteLine(sSoDienThoai);
        //        #endregion

        //        #region "   PHIEU"
        //        ///////////////////////////////================================================
        //        psrlCOMport.Write(Print_Align_Center);
        //        psrlCOMport.Write(Print_Font_Normal_40CharPerRow);

        //        psrlCOMport.Write(((char)(29)).ToString() + ((char)(92)).ToString() + '\n' + ((char)(1)).ToString());
        //        psrlCOMport.Write(Print_Align_Center);
        //        psrlCOMport.Write(Print_Font_Normal_40CharPerRow);
        //        psrlCOMport.WriteLine(new String('=', 56));

        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 

        //        ///////////////////////////////PHIEU
        //        psrlCOMport.WriteLine(this.f_splitString2Column(ocpublic.RemoveSign4VietnameseString(_drPhieu["OBJNAME"] + ""), "", 56));

        //        string sHD = _drPhieu["OBJID"] + "";
        //        sHD = int.Parse(sHD.Substring(4)) + "";
        //        psrlCOMport.WriteLine(this.f_splitString2Column(_drPhieu["NGAYHH"] + "", "HD:" + sHD, 56));
        //        psrlCOMport.WriteLine(new String('=', 56));

        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        #endregion

        //        #region "   CHI TIET PHIEU"
        //        ///////////////////////////////CHI TIET PHIEU
        //        psrlCOMport.Write(Print_Align_Left);
        //        int i1 = 32, i2 = 7, i3 = 17;   // = 56
        //        psrlCOMport.WriteLine(this.f_splitString4Column("ITem", "Price", "QTy", "Amount", i1, i2, i3));
        //        psrlCOMport.WriteLine(new String('-', 56));

        //        string sTenHang = "";
        //        string sDonGia = "";
        //        string sSoLuong = "";
        //        string sThanhTien = "";
        //        for (int _ir = 0; _ir < _tbPhieuCT.Rows.Count; _ir++)
        //        {
        //            sTenHang = "";
        //            sDonGia = "";
        //            sSoLuong = "";
        //            sThanhTien = "";
        //            /////////////////
        //            sTenHang = ocpublic.RemoveSign4VietnameseString(_tbPhieuCT.Rows[_ir]["OBJNAME"] + "");
        //            if (_tbPhieuCT.Rows[_ir]["DON_GIA"] + "" != "")
        //                sDonGia = int.Parse(_tbPhieuCT.Rows[_ir]["DON_GIA"] + "").ToString("N0");
        //            if (_tbPhieuCT.Rows[_ir]["SO_LUONG"] + "" != "")
        //            {
        //                if (_tbPhieuCT.Rows[_ir]["SO_LUONG"].ToString().IndexOf(".") > 0)
        //                    sSoLuong = float.Parse(_tbPhieuCT.Rows[_ir]["SO_LUONG"] + "").ToString("N2");
        //                else
        //                    sSoLuong = float.Parse(_tbPhieuCT.Rows[_ir]["SO_LUONG"] + "").ToString("N0");
        //            }
        //            if (_tbPhieuCT.Rows[_ir]["THANH_TIEN"] + "" != "")
        //                sThanhTien = float.Parse(_tbPhieuCT.Rows[_ir]["THANH_TIEN"] + "").ToString("N0");

        //            psrlCOMport.WriteLine(this.f_splitString4Column(sTenHang, sDonGia, sSoLuong, sThanhTien, i1, i2, i3));
        //        }

        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        #endregion

        //        #region "   PHIEU.TINH TIEN"
        //        ///////////////////////////////FOOT PAGE
        //        psrlCOMport.WriteLine(new String('-', 56));
        //        string sChietKhau_PhanTram = "";
        //        string sVAT_PhanTram = "";
        //        string sTienTip_PhanTram = "";
        //        string sPhiDichVu_PhanTram = "";
        //        string sChietKhau = "";
        //        string sVAT = "";
        //        string sTienTip = "";
        //        string sPhiDichVu = "";

        //        // -==# -==# -==# -==# -==# -==# -==#CK -==# -==# -==# -==# -==# -==# -==# -==# -==# -==#S

        //        if (_drPhieu["CK_PHANTRAM"] + "" != "0" && _drPhieu["CK_PHANTRAM"] + "" != "")
        //            sChietKhau_PhanTram = " (" + _drPhieu["CK_PHANTRAM"] + "%)";

        //        if (_drPhieu["CK_TIEN"] + "" != "0" && _drPhieu["CK_TIEN"] + "" != "")
        //            sChietKhau = int.Parse(_drPhieu["CK_TIEN"] + "").ToString("N0");

        //        // -==# -==# -==# -==# -==# -==# -==#VAT -==# -==# -==# -==# -==# -==# -==# -==# -==# -==#

        //        if (_drPhieu["VAT_PHANTRAM"] + "" != "0" && _drPhieu["VAT_PHANTRAM"] + "" != "")
        //            sVAT_PhanTram = " (" + _drPhieu["VAT_PHANTRAM"] + "%)";

        //        if (_drPhieu["VAT_TIEN"] + "" != "0" && _drPhieu["VAT_TIEN"] + "" != "")
        //            sVAT = int.Parse(_drPhieu["VAT_TIEN"] + "").ToString("N0");

        //        // -==# -==# -==# -==# -==# -==# -==#TTIEP -==# -==# -==# -==# -==# -==# -==# -==# -==# -==#

        //        if (_drPhieu["TTIEP_PHANTRAM"] + "" != "0" && _drPhieu["TTIEP_PHANTRAM"] + "" != "")
        //            sTienTip_PhanTram = " (" + _drPhieu["TTIEP_PHANTRAM"] + "%)";

        //        if (_drPhieu["TTIEP_TIEN"] + "" != "0" && _drPhieu["TTIEP_TIEN"] + "" != "")
        //            sTienTip = int.Parse(_drPhieu["TTIEP_TIEN"] + "").ToString("N0");

        //        // -==# -==# -==# -==# -==# -==# -==#PHU_THU -==# -==# -==# -==# -==# -==# -==# -==# -==# -==#

        //        if (_drPhieu["PHU_THU_PHANTRAM"] + "" != "0" && _drPhieu["PHU_THU_PHANTRAM"] + "" != "")
        //            sPhiDichVu_PhanTram = " (" + _drPhieu["PHU_THU_PHANTRAM"] + "%)";

        //        if (_drPhieu["PHU_THU"] + "" != "0" && _drPhieu["PHU_THU"] + "" != "")
        //            sPhiDichVu = int.Parse(_drPhieu["PHU_THU"] + "").ToString("N0");

        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==#

        //        if (sChietKhau != "" || sVAT != "" || sTienTip != "" || sPhiDichVu != "")
        //        {
        //            psrlCOMport.WriteLine(this.f_splitString2Column("Net total", int.Parse(_drPhieu["THANH_TIEN"] + "").ToString("N0"), 56));
        //            if (sChietKhau != "")
        //                psrlCOMport.WriteLine(this.f_splitString2Column("Discount" + sChietKhau_PhanTram, sChietKhau + "", 56));
        //            if (sVAT != "")
        //                psrlCOMport.WriteLine(this.f_splitString2Column("Vat" + sVAT_PhanTram, sVAT + "", 56));
        //            if (sTienTip != "")
        //                psrlCOMport.WriteLine(this.f_splitString2Column("Tip" + sTienTip_PhanTram, sTienTip + "", 56));
        //            if (sPhiDichVu != "")
        //                psrlCOMport.WriteLine(this.f_splitString2Column("Service charge" + sPhiDichVu_PhanTram, sPhiDichVu + "", 56));
        //            psrlCOMport.WriteLine(new String('-', 56));
        //        }
        //        psrlCOMport.WriteLine(this.f_splitString2Column("Final total", int.Parse(_drPhieu["TONG_TIEN"] + "").ToString("N0"), 56));
        //        #endregion

        //        #region "   CHAN TRANG.2"
        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        // -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# -==# 
        //        /////////////////////////////// ========================================
        //        psrlCOMport.WriteLine(new String('=', 56));
        //        psrlCOMport.WriteLine("Cashier: " + _drPhieu["NGUOI_LAP"]);
        //        psrlCOMport.WriteLine("Thank you very much and see you again!");
        //        psrlCOMport.WriteLine("");
        //        psrlCOMport.WriteLine(((char)(29)).ToString() + ((char)(86)).ToString() + ((char)(66)).ToString() + ((char)(1)).ToString()); //Ngắt trang
        //        #endregion
        //    }
        //    catch (Exception ex)
        //    {
        //        LPV_POS.Module.MessageBox_LPV.Show("In report không thành công.\n" + ex.Message, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Error);
        //    }
        //    #endregion
        //}

        #region "   f_splitString4Column"
        string f_splitString4Column(string a, string b, string c, string d, int i1, int i2, int i3)
        {//i1: 32; i2:7; i3: 17
            string str = "";
            str = a;
            str += new cpublic().Spacestring(i1 - a.Length - b.Length);
            str += b;
            str += new cpublic().Spacestring(i2 - c.Length);
            str += c;
            str += new cpublic().Spacestring(i3 - d.Length);
            str += d;
            return str;
        }
        #endregion

        #region "   f_splitString2Column"
        string f_splitString2Column(string a, string b, int i)
        {//i: 56
            string str = "";
            str = a;
            str += new cpublic().Spacestring(i - a.Length - b.Length);
            str += b;
            return str;
        }
        #endregion
        #endregion---------------end IN BILL TINH DIEM KHACH HANG ----------------

        #region "   KiemTra The"
        void Kiem_Tra_The(object sender, EventArgs e)
        {
            if (sender != null)
            {
                mh_so omh_so = (mh_so)sender;
                string The_Vip_Ma = omh_so.txt_ketqua.Text;
                string sSQL = "SELECT 1 FROM DM_THE WHERE CODE LIKE '" + The_Vip_Ma + "'";

                DataTable tbTheVIP = new thuvien().SP_SelectDataTable("SP_EXECUTESQL", new string[] { "@sSQL" }, new object[] { sSQL });
                if (tbTheVIP.Rows.Count == 0)
                {
                    omh_so.DialogResult = DialogResult.No;
                    new mh_thongbao("MÃ SỐ không hợp lệ", 2).ShowForm();
                }
                else
                {
                    omh_so.DialogResult = DialogResult.OK;
                    omh_so.Dispose();
                }
            }
        }
        #endregion

        int Load_KhuVuc_Default()
        {
            string KHUVUC_MA = new cpublic().Registry_Get(this.Name + "KHUVUC_DEFAULT");

            DataTable tbKhuVuc = (DataTable)grdKhuVuc.DataSource;
            if (KHUVUC_MA != "")
            {
                int iHandle = -1;
                for (iHandle = 0; iHandle < tbKhuVuc.Rows.Count; iHandle++)
                    if (tbKhuVuc.Rows[iHandle]["OBJID"] + "" == KHUVUC_MA)
                        return iHandle;
            }
            return -1;
        }

        private void lblDatBan_Click(object sender, EventArgs e)
        {
            if (sender != null)
            if (((System.Windows.Forms.Control)sender).Text == "") return;
            if (Variable.username == "") return;
            if (ochon == chon.Dat_Ban)//2011
                this.setNoneMesssage();
            else
            {
                    switch (str_lang)
                    { 
                        case "vi-VN":
                            lblMessage_sodoban.Text = "Thông tin đặt bàn";
                            break;
                        case "en-US":
                            lblMessage_sodoban.Text = "Booking table information";
                            break;
                        
                    }
               // lblMessage_sodoban.Text = "Thông tin đặt bàn";
                ochon = chon.Dat_Ban;
            }
        }

        private void lblDatBan_Huy_Click(object sender, EventArgs e)
        {
            if (lblDatBan_Huy_sodoban.Text != "")
            {
                if (Variable.username == "") return;
                if (ochon == chon.Dat_Ban_Huy)//2011
                    this.setNoneMesssage();
                else
                {
                    switch (str_lang)
                    {
                        case "vi-VN":
                            lblMessage_sodoban.Text = "Hủy thông tin đặt bàn";
                            break;
                        case "en-US":
                            lblMessage_sodoban.Text = "Canle booking table information";
                            break;
                          //  lblMessage_sodoban.Text = "Hủy thông tin đặt bàn";
                           
                    }
                    ochon = chon.Dat_Ban_Huy;
                }
            }
        }

        #region "   NhanVien_PhucVu"
        private void label8_Click(object sender, EventArgs e)
        {
            if (sender != null)
            if (((System.Windows.Forms.Control)sender).Text == "") return;
            if (label8_sodoban.Text.Trim() != "")
            {
                if (ochon == chon.NhanVien_PhucVu)//2011
                    this.setNoneMesssage();
                else
                {
                    switch (str_lang)
                    {
                        case "vi-VN":
                            lblMessage_sodoban.Text = "Chọn nhân viên phục vụ";
                            break;
                        case "en-US":
                            lblMessage_sodoban.Text = "Select staff";
                            break;
                        //  lblMessage_sodoban.Text = "Hủy thông tin đặt bàn";

                    }
                    ochon = chon.NhanVien_PhucVu;
                }
            }
        }
        #endregion

        #region "   Load_So Do ban"
        void Load_Menu_Bottom()
        {
            cpublic ocpublic = new cpublic();
            foreach (System.Windows.Forms.Control ctrl in panel_SoDoBan.Controls)
                ocpublic.loadControl_FontColor("menufunction" + ctrl.Name, ctrl);
        }
        #endregion

        #region "   So_Khach"
        private void lbl1_sodoban_Click(object sender, EventArgs e)
        {
            if (sender != null)
            if (((System.Windows.Forms.Control)sender).Text == "") return;
            if (lbl1_sodoban.Text.Trim() != "")
            {
                if (ochon == chon.So_Khach)//2011
                    this.setNoneMesssage();
                else
                {
                    switch (str_lang)
                    {
                        case "vi-VN":
                            lblMessage_sodoban.Text = "Nhập số khách";
                            break;
                        case "en-US":
                            lblMessage_sodoban.Text = "Enter the number of customers";
                            break;
                        //  lblMessage_sodoban.Text = "Hủy thông tin đặt bàn";

                    }
                    ochon = chon.So_Khach;
                }
            }
        }
        #endregion

        private void pnlSoDoBan_Paint(object sender, PaintEventArgs e)
        {

        }

        void Reset_pnlSoDoBan()
        {
            this.groupBox1.Controls.Remove(this.pnlSoDoBan);
            this.pnlSoDoBan = new System.Windows.Forms.Panel();            
            this.pnlSoDoBan.AutoScroll = true;
            this.pnlSoDoBan.BackgroundImage = global::LPV_POS.Properties.Resources.back_banhang;
            //this.pnlSoDoBan.BackgroundImageLayout = ImageLayout.Stretch;
            this.pnlSoDoBan.Location = new System.Drawing.Point(2, 61);
            this.pnlSoDoBan.Name = "pnlSoDoBan";
            this.pnlSoDoBan.Size = new System.Drawing.Size(850, 602);
            this.pnlSoDoBan.TabIndex = 14;
            this.pnlSoDoBan.Paint += new System.Windows.Forms.PaintEventHandler(this.pnlSoDoBan_Paint);
            this.pnlSoDoBan.DragDrop += new DragEventHandler(pnlSoDoBan_DragDrop);
            this.pnlSoDoBan.Dock = DockStyle.Fill;
            //this.pnlSoDoBan.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
            //                | System.Windows.Forms.AnchorStyles.Left)
            //                | System.Windows.Forms.AnchorStyles.Right)));
            //this.Controls.Add(this.pnlSoDoBan);
            this.groupBox1.Controls.Add(this.pnlSoDoBan);
        }

        #region "   DangNhap"
        void DangNhap(object sender, EventArgs e)
        {
            try
            {
                mh_so omh_so = (mh_so)sender;
                string sUsername = omh_so.txt_ketqua.Text.Trim();

                //this.bton_DangNhap_Click(null, null);
                string sSQL = "SELECT * FROM DM_DANGNHAP";
                thuvien othuvien = new thuvien();
                DataTable tbDM_DANGNHAP = othuvien.SP_SelectDataTable("SP_EXECUTESQL",
                                                                        new string[] { "@sSQl" },
                                                                        new object[] { sSQL });
                if (tbDM_DANGNHAP.Select("USERNAME LIKE '" + sUsername.Trim() + "'").Length > 0)
                {
                    DataRow dr = tbDM_DANGNHAP.Select("USERNAME LIKE '" + sUsername + "'")[0];

                    Variable.iquyen = int.Parse("0" + dr["IQUYEN"]);
                    Variable.username = sUsername.Trim();

                }
                else
                {
                    new mh_thongbao("Mã số không tồn tại.", 2).ShowDialog();
                    omh_so.DialogResult = DialogResult.Yes;
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
        }
        #endregion

        #region "mo ket"
        private void lbel_moket_Click(object sender, EventArgs e)
        {
            if (sender != null)
            if (((System.Windows.Forms.Control)sender).Text == "") return;
            try
            {
                Variable oVariable = new Variable();
                oVariable.Get_DM_MAYIN_BIENNHAN();
                if (oVariable.SerialPort_Open_Receipt())//mở cổng COM
                {
                    foreach (SerialPort_LPV oSerialPort_LPV in Variable.gsrlCOMBillport)
                    {
                        if (oSerialPort_LPV != null)
                        {
                            if (!oSerialPort_LPV.IsOpen)
                                oSerialPort_LPV.Open();
                            //  ---------------- Mở ket ---------------------
                            oSerialPort_LPV.Write(((char)(27)).ToString() + "p" + '\0' + ((char)(100)).ToString() + ((char)(250)).ToString());
                            //  ---------------- Mở ket ---------------------

                            if (oSerialPort_LPV.IsOpen)
                                oSerialPort_LPV.Close();
                        }
                        else
                        {
                            System.Drawing.Printing.PrinterSettings cls = new System.Drawing.Printing.PrinterSettings();
                            string sPrinterDefault = cls.PrinterName;
                            LPV_CASH_DRAWER.OpenCashDrawer(sPrinterDefault);
                        }

                    }
                }

            }
            catch (Exception)
            {
                Mod_messagebox mes = new Mod_messagebox();
                mes.messagebox_pos("LPV-POS", "Máy in không kết nối với ket.", loaithongbao.canhbao.GetHashCode());
                return;
            }
        }
        #endregion


        #region "   MouseEvent - MouseDown - MouseMove"
        System.Windows.Forms.Control dragControl = null;
        private System.Windows.Forms.Control newControl = null;
        private void Label_MouseDown(object sender, MouseEventArgs e)
        {
            //newControl = simpleButton1.GetItemAt(e.X, e.Y);
            newControl = (System.Windows.Forms.Control)sender;
            //newControl.BackColor = Color.Azure;//mau lblBottom
            //foreach (System.Windows.Forms.Control ctr in newControl.Parent.Controls)
            //    if (ctr.ToString().IndexOf("Label") > 0)
            //        ctr.BackColor = newControl.BackColor;//mau lblTop
        }
        private void Label_MouseMove(object sender, MouseEventArgs e)
        {
            if (newControl == null || e.Button != MouseButtons.Left)
                return;
            dragControl = new System.Windows.Forms.Control();
            dragControl.Name = Guid.NewGuid().ToString();
            //dragControl.Control = new TextEdit();
            dragControl.Name = Guid.NewGuid().ToString();
            dragControl.Text = newControl.Text;
            ((System.Windows.Forms.Control)sender).DoDragDrop(dragControl, DragDropEffects.Copy);

        }
        private void Label_GiveFeedback(object sender, GiveFeedbackEventArgs e)
        {
            e.UseDefaultCursors = false;
        }

        #endregion

        #region "   GragEvent"
        #region "   DragDrop - kéo thả"
        private void label_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                if (newControl.Name == ((System.Windows.Forms.Control)sender).Name)
                    return;
                //if (CanRecycleDragItem())
                {
                    ((System.Windows.Forms.Control)sender).BackColor = bColor;
                    if (((System.Windows.Forms.Control)sender).ToString().IndexOf("Label") > 0)
                        foreach (System.Windows.Forms.Control ctr in ((System.Windows.Forms.Control)sender).Parent.Controls)
                            if (ctr.ToString().IndexOf("Label") > 0)
                                ctr.BackColor = ((System.Windows.Forms.Control)sender).BackColor;
                    //
                    newControl.BackColor = bColor;
                    foreach (System.Windows.Forms.Control ctr in newControl.Parent.Controls)
                        if (ctr.ToString().IndexOf("Label") > 0)
                            ctr.BackColor = newControl.BackColor;
                    //
                    System.Windows.Forms.Control control = dragControl;
                    //dragControl.Parent.Remove(dragControl);
                    if (control != null)
                    {
                        control.Parent = null;
                        control.Dispose();
                    }
                    dragControl = null;
                }
            }
            catch (Exception ex)
            {
                string s = ex.Message;
            }
            finally
            {
                Cursor = Cursors.Default;
            }
            this.KiemTra_ChuyenBan_TachGopBan(newControl, ((System.Windows.Forms.Control)sender));
        }
        #endregion

        #region "   DragLeave - kéo ra ngoài vùng chọn"
        private void label_DragLeave(object sender, EventArgs e)
        {
            //dragControl = (System.Windows.Forms.Control)sender;
            if (newControl.Name != ((System.Windows.Forms.Control)sender).Name)
            {
                ((System.Windows.Forms.Control)sender).BackColor = bColor;
                if (((System.Windows.Forms.Control)sender).ToString().IndexOf("Label") > 0)
                    foreach (System.Windows.Forms.Control ctr in ((System.Windows.Forms.Control)sender).Parent.Controls)
                        if (ctr.ToString().IndexOf("Label") > 0)
                            ctr.BackColor = ((System.Windows.Forms.Control)sender).BackColor;
            }
        }
        #endregion

        #region "   DragEnter - Kéo trong vùng chọn"
        private void label_DragEnter(object sender, DragEventArgs e)
        {//kéo ngang qua
            if (newControl.Name != ((System.Windows.Forms.Control)sender).Name)
            {
                ((System.Windows.Forms.Control)sender).BackColor = Color.Lime;
                if (((System.Windows.Forms.Control)sender).ToString().IndexOf("Label") > 0)
                    foreach (System.Windows.Forms.Control ctr in ((System.Windows.Forms.Control)sender).Parent.Controls)
                        if (ctr.ToString().IndexOf("Label") > 0)
                            ctr.BackColor = ((System.Windows.Forms.Control)sender).BackColor;
            }
            //if (CanRecycleDragItem())
            {
                //label1.ImageIndex = 1;
                e.Effect = DragDropEffects.Copy;

                //string sp = Application.StartupPath + "\\..\\..\\Images\\move.ico";
                string sp = @"C:\WINDOWS\Cursors\3dwno.cur";

                Cursor = new Cursor(sp);
                //Cursor = new Cursor(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("Drag_Grop.Images.delete.ico"));
            }
        }
        #endregion


        protected bool CanRecycleDragItem()
        {
            if (dragControl == null) return false;
            return true;
        }

        Color bColor;
        #endregion

        private void pnlSoDoBan_DragDrop(object sender, DragEventArgs e)
        {
            newControl.BackColor = bColor;
            foreach (System.Windows.Forms.Control ctr in newControl.Parent.Controls)
                if (ctr.ToString().IndexOf("Label") > 0)
                    ctr.BackColor = newControl.BackColor;
        }

        void KiemTra_ChuyenBan_TachGopBan(System.Windows.Forms.Control ctrlFrom, System.Windows.Forms.Control ctrlTo)
        {
            int iTrangThai = this.KiemTra_ChuyenBan_TachGopBan1_GetTrangThai_Ban(ctrlFrom.Tag + "");
            if (iTrangThai == 0)
                return;//ban chưa ORDER
            else if (iTrangThai >= 2)
            {//có 2 phiếu trở lên
                //iTrangThai += this.KiemTra_ChuyenBan_TachGopBan1_GetTrangThai_Ban(ctrlTo.Tag + "");
                //if (iTrangThai > 2)
                {
                    mh_banhang1_TachGopBan omh_banhang1_TachGopBan = new mh_banhang1_TachGopBan(ctrlFrom.Tag + "", Variable.ngay_gio_hienhanh, ctrlTo.Tag + "");
                    omh_banhang1_TachGopBan.ShowDialog();
                    if (omh_banhang1_TachGopBan.DialogResult == DialogResult.OK)
                    {
                        this.gridView1_FocusedRowChanged(null, null);
                        this.Client_Server_Send();//2011
                    }
                    return;
                }
            }            
            //string sThongBao = "Gộp bàn thành công";
            //if (iTrangThai == 0)
            //    sThongBao = "Chuyển bàn thành công";

            iTrangThai = this.KiemTra_ChuyenBan_TachGopBan2_SAVE(ctrlFrom.Tag + "", ctrlTo.Tag + "");
            if (iTrangThai > 0)
            {
                //MessageBox_LPV.Show(sThongBao);
                this.gridView1_FocusedRowChanged(null, null);
                this.Client_Server_Send();//2011
            }
        }

        int KiemTra_ChuyenBan_TachGopBan1_GetTrangThai_Ban(string sBan_Ma)
        {
            thuvien othuvien = new thuvien();
            string sSQL = "SELECT COUNT(1) FROM BH_PHIEU_TMP WHERE DM_BAN_MA LIKE '" + sBan_Ma + "' ";
            return othuvien.SP_SelectReturnOne("SP_EXECUTESQL",
                                         new string[] { "@sSQL" },
                                         new object[] { sSQL });
        }

        int KiemTra_ChuyenBan_TachGopBan2_SAVE(string sBan_Ma_From, string sBan_Ma_To)
        {//CHUYEN BAN
            thuvien othuvien = new thuvien();
            int irt = othuvien.SP_Update("sp_mh_banhang",
                                        new string[] { "@flag", "@DM_BAN_MA", "@DM_BAN_MA2" },
                                        new object[] { 12, sBan_Ma_From, sBan_Ma_To});
            return irt;
        }

        private void mh_banhang_Activated(object sender, EventArgs e)
        {

        }
        //-------27/06/2012----------------------------
        #region " Hiển thị thông tin đặt bàn "
        private void lbel_Thongtindatban_Click(object sender, EventArgs e)
        {
            frmTHONG_TIN_DAT_BAN fr = new frmTHONG_TIN_DAT_BAN();
            fr.ShowDialog();
        }
        #endregion
    }
}